import os
from django.db import models

from conf.my_settings import IMAGE_DIR
from mental_backend.settings import MEDIA_URL, BASE_DIR
from utils.tools import hash_password, verify_password, get_uuid, get_now

AVATAR_PATH = "avatar/"
class User(models.Model):
	uid = models.AutoField(verbose_name='用户id', primary_key=True, unique=True)
	username = models.CharField(verbose_name='用户账号', unique=True, max_length=30, blank=False)
	avatar = models.ImageField(verbose_name='用户头像', upload_to=f"{IMAGE_DIR}{AVATAR_PATH}",null=True, blank=True)
	password = models.CharField(verbose_name='用户密码', max_length=255, null=False, blank=False)
	nickname = models.CharField(verbose_name='用户昵称', max_length=255, null=True, blank=True)
	create_time = models.CharField(verbose_name="注册时间", max_length=255, null=True)
	update_time = models.CharField(verbose_name="更新时间", max_length=255, null=True)
	
	def avatar_url(self):
		if self.avatar and hasattr(self.avatar, "url"):
			return self.avatar.url
		else:
			return f"/{MEDIA_URL}{IMAGE_DIR}{AVATAR_PATH}default.png"
	
	def update_avatar(self, new_avatar):
		if self.avatar and hasattr(self.avatar, "url"):
			try: os.remove(os.path.join(BASE_DIR, self.avatar.url))
			except FileNotFoundError: pass
		self.avatar = new_avatar
		ext = self.avatar.name[self.avatar.name.rfind("."):]
		self.avatar.name = f"{get_uuid()}{ext}"
		self.save()
		return self.avatar_url()
		
	def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
		self.update_time = get_now()
		super().save()
	
	# 加密保存密码
	def create(self):
		self.password = hash_password(self.password)
		if not self.nickname: self.nickname = f"user_{self.username}"
		self.create_time = get_now()
		self.save()
	
	# 验证密码
	def verify(self, password):
		return verify_password(password, self.password)
	
	class Meta:
		verbose_name = "用户"  # 模型名称
		verbose_name_plural = "用户列表"  # 模型复数名称
		
	def __str__(self):
		return str(self.username)
